package gat.application.log.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bitsun.core.common.exception.AppException;
import com.bitsun.core.common.exception.ErrorCode;
import com.bitsun.core.common.persistence.BasePService;
import com.bitsun.core.common.persistence.IPService;
import com.bitsun.core.common.persistence.Pager;
import com.bitsun.core.common.persistence.QueryParamUtils;
import com.google.common.base.CaseFormat;
import gat.application.log.LogService;
import gat.convertor.log.LogReqDtoConvertor;
import gat.convertor.log.LogResDtoConvertor;
import gat.dto.req.log.LogReqDto;
import gat.dto.res.log.LogResDto;
import gat.infrastructure.persistence.dao.log.LogMapper;
import gat.infrastructure.persistence.po.log.LogPo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
 * 示例表，应用（业务编排）层实现
 * @author: yanshukeji-java
 * @email: yanshukeji-java
 */
@Slf4j
@Service("logAppService")
@Transactional(rollbackFor = Exception.class)
public class LogServiceImpl implements LogService {

    @Autowired
    private LogReqDtoConvertor logReqDtoConvertor;

    @Autowired
    private LogResDtoConvertor logResDtoConvertor;

    private IPService<LogPo> logPoService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    public LogServiceImpl(LogMapper logMapper) {
        this.logPoService = new BasePService(logMapper);
    }



    @Override
    public LogResDto save(LogReqDto reqDto) {
        LogPo po = logReqDtoConvertor.dto2Po(reqDto);
        logPoService.save(po);
        LogResDto resDto = logResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean deleteByIds(String ids) {
        try {
            List<Long> idLongList =
            Arrays.asList(ids.split(",")).stream().map(s -> NumberUtils.createLong(s.trim())).collect(Collectors.toList());
            return logPoService.removeByIds(idLongList);
        } catch (Exception e) {
            throw new AppException("参数错误：" + ids, ErrorCode.pc("417"), e);
        }
     }

    @Override
    public Pager<LogResDto> doPager(Map<String, Object> params) {
        Pager<LogPo> poPager = logPoService.queryPage(params, LogPo.class);
        Pager<LogResDto> resDtoPager = logResDtoConvertor.convertPoPager2ResDtoPager(poPager);
        return resDtoPager;
    }

    @Override
    public LogResDto selectOne(Long id) {
        LogPo po = logPoService.getById(id);
        LogResDto resDto = logResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public LogResDto selectOne(Map<String, Object> params) {
        QueryWrapper queryWrapper = QueryParamUtils.queryWrapper4eq(LogPo::new, params);
        queryWrapper.last(" limit 1");
        LogPo po = logPoService.getOne(queryWrapper);
        LogResDto resDto = logResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean updateProps(Long id, Map<String, Object> params) {
        UpdateWrapper<LogPo> updateWrapper = QueryParamUtils.updateWrapper4Map(LogPo::new, id, params);
        return logPoService.update(new LogPo(), updateWrapper);
        }

    @Override
    public boolean updateProps(Long id, LogReqDto reqDto) {
        LogPo po = logReqDtoConvertor.dto2Po(reqDto);
        po.setId(id);
        return logPoService.updateById(po);
    }


    @Override
    public boolean updateAllProps(Long id, LogReqDto reqDto) {
        UpdateWrapper<LogPo> updateWrapper = Wrappers.update();
        updateWrapper.eq("id", id);
        Field[] fields = LogReqDto.class.getDeclaredFields();
        Arrays.stream(fields).filter(f -> !Modifier.isStatic(f.getModifiers())).forEach(field -> {
        try {
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), LogReqDto.class);
        Method getMethod = propertyDescriptor.getReadMethod();
        String fileNameCamel = getMethod.getName().substring(3);
        String fileNameUnderline = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fileNameCamel);
        updateWrapper.set(fileNameUnderline, getMethod.invoke(reqDto));
        } catch (Exception ex) {
        log.warn("属性不存在get方法："+field.getName(),ex);
        }
        });
        return logPoService.update(new LogPo(), updateWrapper);
    }

    @Override
    public Pager<LogResDto> getLogList(LogReqDto reqDto) {
        Integer currentPage = Optional.ofNullable(reqDto.getCurrentPage()).orElse(1);
        Integer pageSize = Optional.ofNullable(reqDto.getPageSize()).orElse(10);
        QueryWrapper<LogPo> qw = new QueryWrapper<>();
        qw.lambda().like(StringUtils.isNotBlank(reqDto.getDescription()), LogPo::getDescription, reqDto.getDescription());
        qw.lambda().orderByDesc(LogPo::getCreateTime);
        Page<LogPo> page = logPoService.page(new Page<>(currentPage, pageSize), qw);
        return logResDtoConvertor.convertPoPager2ResDtoPager(
                new Pager<>(page.getRecords(), page.getTotal(), page.getSize(), page.getCurrent()));
    }

}